<template>
  <view :data-theme="globPrimary">
    <view class="edu-navbar-fixed" :style="{ height: globStatusBarHeight + 'px' }"></view>
    <view :style="{ width: '100%', height: globStatusBarHeight + 'px' }"></view>
    <!-- #ifndef APP-PLUS -->
    <u-navbar
      class="navbar-wrapper"
      :class="{ active: opacity < 1 }"
      :is-back="false"
      :border-bottom="false"
      back-icon-color="#fff"
      :immersive="true"
      :background="backgroundColor"
    >
      <view class="round" @tap="onBack"
        ><u-icon name="nav-back" color="#fff" size="30"></u-icon
      ></view>
      <view v-show="opacity >= 1" class="navbar-title u-line-1">课程详情</view>
      <view slot="right" class="right">
        <view class="round" @click="onCollectedChange">
          <image
            class="img"
            src="/pageCourse/static/images/course_collect_pre.png"
            v-if="collected"
          ></image>
          <image class="img" src="/pageCourse/static/images/course_collect_icon.png" v-else></image>
        </view>
        <view class="round" @click="inviteBargain">
          <image class="img" src="/pageCourse/static/images/course_share_icon.png"></image>
        </view>
      </view>
    </u-navbar>
    <!-- #endif -->
    <mescroll-body
      :sticky="true"
      :down="{ use: false }"
      :up="{ empty: { use: false }, showLoading: false }"
      :height="mescrollHeight"
      ref="mescrollRef"
      @init="mescrollInit"
      @up="upCallback"
    >
      <view class="header-top u-rela">
        <!-- 音视频 -->
        <template v-if="sectionDataType == 1 || sectionDataType == 2">
          <!-- #ifdef H5 -->
          <cch5VideoPlayer
            ref="refCurrentPlayer"
            :detailsInfo="detailsInfo"
            :course_lock="course_lock"
            @next="getVideoPlayfile"
            v-if="getCurrentPlayItem.section_data.stock == 'bokecc'"
          ></cch5VideoPlayer>
          <aliyunVideoPlayer
            ref="refCurrentPlayer"
            :detailsInfo="detailsInfo"
            :course_lock="course_lock"
            @next="getVideoPlayfile"
            v-else
          ></aliyunVideoPlayer>
          <!-- #endif -->
          <!-- #ifdef MP-WEIXIN || APP-PLUS -->
          <ccwxVideoPlayer
            ref="refCurrentPlayer"
            :detailsInfo="detailsInfo"
            :course_lock="course_lock"
            @next="getVideoPlayfile"
            v-if="getCurrentPlayItem.section_data.stock == 'bokecc'"
          ></ccwxVideoPlayer>
          <mmVideoPlayer
            ref="refCurrentPlayer"
            :detailsInfo="detailsInfo"
            :course_lock="course_lock"
            @next="getVideoPlayfile"
            v-else
          ></mmVideoPlayer>
          <!-- #endif -->
        </template>
        <mmImageText
          v-else-if="sectionDataType == 3"
          ref="refCurrentPlayer"
          @change="handleDocumentChange"
        ></mmImageText>
        <!-- #ifdef H5 || APP-PLUS -->
        <document
          v-else-if="sectionDataType == 4"
          ref="refCurrentPlayer"
          :url="detailsInfo.cover_url"
          @change="handleDocumentChange"
        ></document>
        <!-- #endif -->
        <view class="header-top__image" v-else>
          <edu-image width="100%" :height="415" :src="detailsInfo.cover_url"></edu-image>
        </view>
      </view>
      <view class="header-wrapper">
        <template v-if="!$u.test.empty(detailsInfo)">
          <view class="section" @click="onPick">
            <view class="title u-line-1">{{ detailsInfo.title }}</view>
            <view class="info">
              详情
              <u-icon name="arrow-right"></u-icon>
            </view>
          </view>
          <!-- 班级课不显示 -->
          <view class="progress">
            <view class="title"
              >已完成：{{ `${detailsInfo.finished_num}/${detailsInfo.section_count}` }}</view
            >
            <u-circle-progress
              :percent="percentage(detailsInfo.finished_num, detailsInfo.section_count)"
              inactive-color="#E4E7ED"
              active-color="#67C23A"
              width="50"
              border-width="5"
              duration="500"
              v-show="showProgress"
            >
              <text class="text">{{ `${detailsInfo.learn_rate}%` }}</text>
            </u-circle-progress>
          </view>
        </template>
      </view>
      <u-gap height="8" bg-color="#F7F7F7"></u-gap>
      <view class="tab-wrapper" v-if="!loading">
        <u-sticky :enable="enable">
          <u-tabs-swiper
            ref="uTabs"
            :list="tabList"
            :current="tabCurrent"
            @change="tabsChange"
            :active-color="globPrimaryColor"
            :is-scroll="false"
            :bold="false"
            bar-height="4"
            :bar-style="{ bottom: 0 }"
            class="tab-navbar"
          ></u-tabs-swiper>
          <u-line color="#F7F7F7" />
        </u-sticky>
        <!-- 目录 -->
        <view v-show="swiperCurrent == 'directory'">
          <classesDirectory
            v-if="detailsInfo.course_type == 4"
            ref="courseClasses"
            :course-id="detailsInfo.id"
            :detailsInfo="detailsInfo"
          ></classesDirectory>
          <Section
            v-if="detailsInfo.course_type == 1 || detailsInfo.course_type == 2"
            ref="courseSection"
            :course-id="detailsInfo.id"
            :detailsInfo="detailsInfo"
          ></Section>
        </view>

        <!-- 笔记 -->
        <NoteList ref="courseNote" :detailsInfo="detailsInfo" v-show="swiperCurrent == 'note'">
        </NoteList>

        <!-- 评论 -->
        <Comment
          ref="courseComment"
          :detailsInfo="detailsInfo"
          v-show="swiperCurrent == 'comment'"
        ></Comment>
      </view>
    </mescroll-body>

    <view
      class="note-placeholder"
      v-if="!loading && globNoteSwitch && detailsInfo.course_type != 2"
    >
      <view class="note-bottom">
        <edu-button type="primary" shape="circle" size="medium" @click="onAddNotes"
          >记笔记</edu-button
        >
      </view>
    </view>

    <!-- 笔记输入框 -->
    <noteTextarea ref="noteTextarea" :detailsInfo="detailsInfo"></noteTextarea>

    <edu-user-coupon></edu-user-coupon>
  </view>
</template>

<script>
import Section from '../components/section.vue'
import classesDirectory from '../components/classesDirectory.vue'
import NoteList from '../note/list.vue'
import Comment from '../comment/index.vue'

// #ifdef H5
import aliyunVideoPlayer from './components/aliyunVideoPlayer' // 阿里云播放器
import cch5VideoPlayer from './components/ccVideoPlayer/h5' // cch5播放器
// #endif

// #ifdef MP-WEIXIN || APP-PLUS
import ccwxVideoPlayer from './components/ccVideoPlayer/wx' // ccwx播放器
import mmVideoPlayer from './components/videoPlayer.vue' // 原生播放器
// #endif

import mmImageText from './components/imageText.vue'

/* #ifdef H5 || APP-PLUS */
import document from './components/document'
/* #endif */

import noteTextarea from './components/note-textarea.vue'
import setting from '@/settings/projectSetting.js'
import { mapState, mapGetters } from 'vuex'
import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js'
export default {
  mixins: [MescrollMixin],
  components: {
    classesDirectory,
    Section,
    Comment,
    NoteList,
    // #ifdef H5
    aliyunVideoPlayer,
    cch5VideoPlayer,
    // #endif
    // #ifdef MP-WEIXIN || APP-PLUS
    ccwxVideoPlayer,
    mmVideoPlayer,
    // #endif
    mmImageText,
    /* #ifdef H5 || APP-PLUS */
    document,
    /* #endif */
    noteTextarea,
  },
  data() {
    return {
      setting,
      backgroundColor: {
        backgroundColor: 'transparent',
      },
      opacity: 0,
      detailsInfo: {},
      enable: true,
      tabCurrent: 0, // tabs组件的current值，表示当前活动的tab选项
      swiperCurrent: 'directory', // swiper组件的current值，表示当前那个swiper-item是活动的
      options: {},
      loading: false,
      showProgress: true,
      recentLearnShow: false, // 没有学习记录
      subNVue: null,
      course_lock: 0, // 是否解锁
    }
  },
  computed: {
    ...mapState({
      getCurrentPlayItem: (state) => state.course.currentPlayItem,
    }),
    ...mapGetters({
      globPrimary: 'designSetting/getGlobTheme',
      globPrimaryColor: 'designSetting/getGlobThemeColor',
      globNavbarHeight: 'projectSetting/globNavbarHeight',
      globStatusBarHeight: 'projectSetting/globStatusBarHeight',
      globNoteSwitch: 'projectSetting/getGlobCourseNoteSwitch',
      globCommentSwitch: 'projectSetting/getGlobCourseCommentSwitch',
    }),
    collected() {
      return this.detailsInfo.collected
    },
    tabList() {
      let arr = [{ name: '目录', key: 'directory' }]
      let audition = this.detailsInfo.audition_stat == 1 && this.detailsInfo.is_buy === 0
      if (this.globCommentSwitch) {
        arr.push({ name: '评论', key: 'comment' })
      }
      let course_type = this.detailsInfo.course_type == 1 || this.detailsInfo.course_type == 4
      if (this.globNoteSwitch && course_type) {
        arr.push({ name: '笔记', key: 'note' })
      }
      let directoryIndex = arr.findIndex((item) => item.key == 'directory')
      if (audition) {
        arr[directoryIndex].count = '试看'
      }
      return arr
    },
    // 课时类型
    sectionDataType() {
      if (this.$u.test.empty(this.getCurrentPlayItem)) return 0
      if (
        this.$u.test.empty(this.getCurrentPlayItem.section_data) ||
        this.$u.test.empty(this.getCurrentPlayItem.section_data.data_type)
      )
        return 0
      let type = this.getCurrentPlayItem.section_data.data_type
      return type
    },
    mescrollHeight() {
      let course_type = this.detailsInfo.course_type == 1 || this.detailsInfo.course_type == 4
      let windowHeight = this.$u.sys().windowHeight
      let height = 0
      if (course_type) {
        height = windowHeight - this.globStatusBarHeight - 50
      } else {
        height = windowHeight - this.globStatusBarHeight
      }
      return `${height}px`
    },
  },
  onLoad(options) {
    this.options = options
    this.getDetailsInfo(options.id)

    // #ifdef APP-PLUS
    this.subNVue = uni.getSubNVueById('videoNavbar') // 通过 id 获取 nvue 子窗体
    this.subNVue.show()
    this.subNVue.setStyle({
      position: 'absolute',
      width: '100%',
      height: this.globStatusBarHeight + this.globNavbarHeight + 'px',
      left: '0px',
      right: '0px',
      top: `0px`,
      background: 'transparent',
    })
    // #endif
  },
  onUnload() {
    uni.$off('courseTabUpdate')
    uni.$off('sectionPlayerUpdate')
    uni.$off('sectionPlayerPause')
    // #ifdef APP-PLUS
    uni.$off('subNvue-navbar-page')
    uni.$off('subNvue-navbar-click')
    // #endif
  },
  onHide() {
    this.enable = false
  },
  // 监听页面返回
  onBackPress(options) {
    if (options.from === 'navigateBack') {
      return false
    }
    this.onBack()
    return true
  },
  onPageScroll(e) {
    this.pageScroll(e)
  },
  mounted() {
    uni.$on('courseTabUpdate', () => {
      this.mescroll.resetUpScroll()
    })
    uni.$on('sectionPlayerUpdate', () => {
      this.mescroll.scrollTo(0, 0)
    })
    uni.$on('sectionPlayerUpdate', () => {
      this.getVideoPlayfile()
    })

    // #ifdef APP-PLUS
    uni.$on('subNvue-navbar-click', (type) => {
      if (type == 1) {
        this.onBack()
      } else if (type == 2) {
        this.onCollectedChange()
      } else if (type == 3) {
        this.inviteBargain()
      }
    })
    // #endif
  },
  options: { styleIsolation: 'shared' },
  methods: {
    getDetailsInfo(id) {
      this.loading = true
      this.$edu.api.getCourseDetails(id).then((res) => {
        const { data } = res
        this.detailsInfo = data
        // 如果没有课时id
        if (this.$u.test.empty(this.options.sid)) {
          let item = data.recent_learn
          if (!this.$u.test.empty(item) && data.course_type != 2) {
            // 缓存课时的item
            let sectionData = {
              id: item.section_id,
              course_id: item.course_id,
              section_rate: {
                current_time: item.current_time,
              },
              section_data: item.section_data,
              face_data: item.face_data,
            }
            this.$store.commit('course/setCurrentPlayItem', sectionData)
            this.getVideoPlayfile()
          } else {
            this.$store.commit('course/setCurrentPlayItem', {})
          }
        } else {
          this.getVideoPlayfile()
        }

        // #ifdef APP-PLUS
        uni.$emit('subNvue-navbar-page', {
          collected: this.detailsInfo.collected,
        })
        // #endif
        setTimeout(() => {
          this.loading = false
        }, 200)
      })
    },
    // tabs通知swiper切换
    tabsChange(index) {
      this.tabCurrent = index
      this.swiperCurrent = this.tabList[index].key
      this.$nextTick(() => {
        this.mescroll.resetUpScroll()
        this.mescroll.scrollTo(0, 0)
      })
    },
    // 加载更多
    upCallback(page) {
      if (this.swiperCurrent == 'directory') {
        this.mescroll.endSuccess(0)
      } else if (this.swiperCurrent == 'comment') {
        this.$refs.courseComment.getCommentList(page, this.mescroll)
      } else if (this.swiperCurrent == 'note') {
        this.$refs.courseNote.getNoteList(page, this.mescroll)
      }
    },
    // 导航栏渐变
    pageScroll(e) {
      let color = this.globPrimaryColor
      let tmpY = 240
      if (e.scrollTop > tmpY) {
        this.opacity = 1
      } else {
        this.opacity = (e.scrollTop - 150) / 60
      }
      let rgba = this.$u.colorToRgba(color, this.opacity)
      this.backgroundColor = {
        backgroundColor: rgba,
      }
      // #ifdef APP-PLUS
      if (this.opacity < 1) {
        uni.$emit('subNvue-navbar-page', {
          opacity: 0,
          collected: this.detailsInfo.collected,
        })
      } else {
        uni.$emit('subNvue-navbar-page', {
          opacity: 1,
          collected: this.detailsInfo.collected,
        })
      }
      // #endif
    },
    // 分享
    inviteBargain() {
      this.$edu.judgeLogin(() => {
        this.$u.route('/pageCourse/course/share', {
          type: 1,
          id: this.detailsInfo.id,
        })
      })
    },
    // 收藏
    onCollectedChange() {
      this.$edu.judgeLogin(() => {
        let type = { 1: 'video', 2: 'live', 3: 'offline', 4: 'classes' }
        let courceType = type[this.detailsInfo.course_type]
        if (this.detailsInfo.collected) {
          this.$edu.api
            .deleteCollection({
              source_type: courceType,
              source_id: this.detailsInfo.id,
            })
            .then((res) => {
              this.$u.toast(res.msg)
              this.detailsInfo.collected = 0
              // #ifdef APP-PLUS
              uni.$emit('subNvue-navbar-page', {
                collected: 0,
              })
              // #endif
            })
        } else {
          this.$edu.api
            .createCollection({
              source_type: courceType,
              source_id: this.detailsInfo.id,
            })
            .then((res) => {
              this.$u.toast(res.msg)
              this.detailsInfo.collected = 1
              // #ifdef APP-PLUS
              uni.$emit('subNvue-navbar-page', {
                collected: 1,
              })
              // #endif
            })
        }
      })
    },
    // 添加笔记
    onAddNotes() {
      if (this.detailsInfo.is_buy == 1 || this.getCurrentPlayItem.is_buy == 1) {
        this.$refs.noteTextarea.show = true
      } else {
        this.$u.toast('购买后才能记笔记')
      }
    },
    /**
     * 计算百分比
     * @param   {number} num   分子
     * @param   {number} total 分母
     * @returns {number} 返回数百分比
     */
    percentage(num, total) {
      if (num == 0 || total == 0) {
        return 0
      }
      return Math.round((num / total) * 100)
    },
    // 播放数据
    getVideoPlayfile() {
      let class_id = this.detailsInfo.course_type === 4 ? this.detailsInfo.id : 0
      this.$edu.api
        .getCourseSectionFileurl(this.getCurrentPlayItem.course_id, this.getCurrentPlayItem.id, {
          class_id: class_id,
        })
        .then((res) => {
          const { data } = res
          this.course_lock = data.course_lock

          // 当前播放定位
          this.$store.dispatch('course/setCurrentPlayPosition', {
            ...data.curr_position,
          })
          // 解锁模式,播放时保存已播放的id
          if (data.course_lock == 1) {
            this.$store.commit('course/setPlaySectionLock', this.getCurrentPlayItem.id)
          }
          if (this.sectionDataType == 4) {
            /* #ifdef MP */
            this.recentLearnShow = false
            uni.showLoading({
              title: '加载中',
            })
            uni.downloadFile({
              url: data.fileurl_string,
              success: function (res) {
                let filePath = res.tempFilePath
                uni.openDocument({
                  filePath: filePath,
                  showMenu: true,
                  success: function (res) {
                    console.log('打开文档成功')
                    uni.hideLoading()
                  },
                })
              },
            })
            /* #endif */
            /* #ifdef H5 || APP-PLUS */
            this.$refs.refCurrentPlayer.getPlayerFile(data)
            this.recentLearnShow = true
            /* #endif */
            // #ifdef APP-PLUS
            this.$u.route('/pageCourse/course/pdf')
            // #endif
          } else {
            this.$nextTick(() => {
              this.$refs.refCurrentPlayer.getPlayerFile(data)
              this.recentLearnShow = true
            })
          }
        })
        .catch((err) => {})
    },
    // 文档打开关闭时触发
    handleDocumentChange() {
      this.showProgress = !this.showProgress
      // #ifdef APP-PLUS
      if (this.showProgress) {
        setTimeout(() => {
          this.subNVue.show()
        }, 250)
      } else {
        this.subNVue.hide()
      }
      // #endif
    },
    // 返回上一页
    onBack() {
      let pages = getCurrentPages()
      let page = pages[pages.length - 2]
      let currentPage = pages[pages.length - 1]
      if (this.$u.test.empty(page) || page.route == currentPage.route) {
        this.$u.route({
          type: 'reLaunch',
          url: 'pageCourse/course/details',
          params: {
            id: this.options.id,
          },
        })
      } else {
        this.$u.route({ type: 'back' })
      }
    },
    onPick() {
      this.$u.route({
        type: 'reLaunch',
        url: 'pageCourse/course/details',
        params: {
          id: this.options.id,
        },
      })
    },
  },
  beforeDestroy() {
    // 退出时清除播放定位
    this.$store.dispatch('course/setCurrentPlayPosition', null)
  },
}
</script>

<style lang="scss" scoped>
.edu-navbar-fixed {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  z-index: 100;
  background: #ffffff;
}
.navbar-wrapper {
  .navbar-title {
    position: absolute;
    left: 125px;
    right: 125px;
    font-size: 16px;
    text-align: center;
    font-weight: 500;
    color: #ffffff;
  }
  .u-navbar-inner {
    padding: 0 15px;
  }
  .right {
    display: flex;
  }
  &.active {
    .round {
      background: rgba(0, 0, 0, 0.4);
    }
  }
  .round {
    width: 58rpx;
    height: 58rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    .img {
      width: 29px;
      height: 29px;
    }
  }
  .round + .round {
    margin-left: 15px;
  }
}
.header-top {
  height: 415rpx;
}
.header-image {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  z-index: 900;
}
.header-wrapper {
  padding: 30rpx;
  background-color: #fff;
  .section {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .title {
      width: 600rpx;
      font-size: 32rpx;
      font-weight: 500;
      color: #333333;
    }
    .info {
      display: flex;
      align-items: center;
      font-size: 28rpx;
      font-weight: 400;
      color: $edu-tips-color;
    }
  }
  .progress {
    margin-top: 20rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .title {
      font-size: 28rpx;
      font-weight: 400;
      color: $edu-tips-color;
    }
    .text {
      transform: scale(0.6);
      font-size: 12px;
      font-weight: 400;
      color: $edu-content-color;
    }
  }
}
.tab-navbar {
  /deep/.u-badge {
    background-color: $edu-type-success;
    padding: 6rpx 13rpx;
    border-radius: 9rpx 9rpx 9rpx 0;
  }
}

.tab-wrapper {
  background-color: #ffffff;
}

.note-placeholder {
  height: 98rpx;
}

.note-bottom {
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 100;
  height: 98rpx;
  background: #ffffff;
  box-shadow: 0px 2px 14px 0px rgba(0, 0, 0, 0.06);
}

.note-wrap {
  position: fixed;
  bottom: 0;
  z-index: 999;

  width: 100%;
  background-color: #ffffff;
  overflow: hidden;
  padding-bottom: 20rpx;
  .textarea {
    height: 190rpx;
    width: 690rpx;
    margin: 72rpx auto 42rpx;
    border: 1px solid #e4e7ed;
    padding: 24rpx 10rpx 8rpx 24rpx;
    border-radius: 8rpx;
    textarea {
      width: 100%;
      height: 110rpx;
    }
    .font_num {
      height: 32rpx;
      width: 100%;
      text-align: right;
      .xianzhi {
        font-size: 24rpx;
        color: #909399;
      }
    }
  }
  .isopen {
    height: 40rpx;
    width: 90%;
    margin-left: 5%;
    // margin-left: 42rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .fabu {
      font-size: 32rpx;
    }
  }
}
</style>
